/**
 * 图片处理工具类
 * 提供图片粘贴、压缩、格式转换等功能
 */

/**
 * 图片压缩选项
 */
export interface ImageCompressOptions {
  maxWidth?: number
  maxHeight?: number
  quality?: number
  format?: 'jpeg' | 'png' | 'webp'
}

/**
 * 处理粘贴事件中的图片
 * @param clipboardData 剪贴板数据
 * @returns Promise<File[]> 图片文件数组
 */
export const handlePastedImages = async (clipboardData: DataTransfer): Promise<File[]> => {
  const images: File[] = []

  console.log('开始处理剪贴板数据')

  for (let i = 0; i < clipboardData.items.length; i++) {
    const item = clipboardData.items[i]
    console.log(`处理项目 ${i}: type=${item.type}, kind=${item.kind}`)

    if (item.type.startsWith('image/')) {
      console.log('发现图片类型:', item.type)
      const file = item.getAsFile()
      if (file) {
        console.log('成功获取图片文件:', file.name, file.size, 'bytes')
        images.push(file)
      } else {
        console.log('无法获取图片文件')
      }
    } else {
      console.log('非图片类型，跳过')
    }
  }

  console.log('最终获取到的图片数量:', images.length)
  return images
}

/**
 * 压缩图片
 * @param file 原始图片文件
 * @param options 压缩选项
 * @returns Promise<Blob> 压缩后的图片Blob
 */
export const compressImage = async (
  file: File,
  options: ImageCompressOptions = {}
): Promise<Blob> => {
  const { maxWidth = 1920, maxHeight = 1080, quality = 0.8, format = 'jpeg' } = options

  return new Promise((resolve, reject) => {
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    const img = new Image()

    img.onload = () => {
      // 计算压缩后的尺寸
      let { width, height } = img

      if (width > maxWidth) {
        height = (height * maxWidth) / width
        width = maxWidth
      }

      if (height > maxHeight) {
        width = (width * maxHeight) / height
        height = maxHeight
      }

      // 设置画布尺寸
      canvas.width = width
      canvas.height = height

      // 绘制图片
      ctx?.drawImage(img, 0, 0, width, height)

      // 转换为Blob
      canvas.toBlob(
        (blob) => {
          if (blob) {
            resolve(blob)
          } else {
            reject(new Error('图片压缩失败'))
          }
        },
        `image/${format}`,
        quality
      )
    }

    img.onerror = () => {
      reject(new Error('图片加载失败'))
    }

    img.src = URL.createObjectURL(file)
  })
}

/**
 * 创建图片预览URL
 * @param blob 图片Blob数据
 * @returns string 预览URL
 */
export const createImagePreviewUrl = (blob: Blob): string => {
  return URL.createObjectURL(blob)
}

/**
 * 释放图片预览URL
 * @param url 预览URL
 */
export const revokeImagePreviewUrl = (url: string): void => {
  URL.revokeObjectURL(url)
}

/**
 * 验证图片文件类型
 * @param file 文件对象
 * @returns boolean 是否为有效的图片文件
 */
export const isValidImageFile = (file: File): boolean => {
  const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml']
  return validTypes.includes(file.type)
}

/**
 * 获取图片文件信息
 * @param file 图片文件
 * @returns Promise<{width: number, height: number, size: number}>
 */
export const getImageInfo = async (
  file: File
): Promise<{ width: number; height: number; size: number }> => {
  return new Promise((resolve, reject) => {
    const img = new Image()

    img.onload = () => {
      resolve({
        width: img.naturalWidth,
        height: img.naturalHeight,
        size: file.size
      })
    }

    img.onerror = () => {
      reject(new Error('无法获取图片信息'))
    }

    img.src = URL.createObjectURL(file)
  })
}

/**
 * 生成图片的Markdown语法
 * @param imageId 图片ID
 * @param altText 替代文本
 * @returns string Markdown图片语法
 */
export const generateImageMarkdown = (imageId: string, altText: string = '图片'): string => {
  return `![${altText}](image://${imageId})`
}

/**
 * 从Markdown内容中提取图片ID
 * @param content Markdown内容
 * @returns string[] 图片ID数组
 */
export const extractImageIds = (content: string): string[] => {
  const imageRegex = /!\[.*?\]\(image:\/\/(.*?)\)/g
  const imageIds: string[] = []
  let match

  while ((match = imageRegex.exec(content)) !== null) {
    imageIds.push(match[1])
  }

  return imageIds
}

/**
 * 格式化文件大小
 * @param bytes 字节数
 * @returns string 格式化后的大小
 */
export const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'

  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

/**
 * 生成唯一的图片文件名
 * @param originalName 原始文件名
 * @returns string 新的文件名
 */
export const generateUniqueImageName = (originalName: string): string => {
  const timestamp = Date.now()
  const random = Math.random().toString(36).substr(2, 6)
  const extension = originalName.split('.').pop() || 'jpg'

  return `image_${timestamp}_${random}.${extension}`
}

/**
 * 检查浏览器是否支持WebP格式
 * @returns Promise<boolean>
 */
export const supportsWebP = (): Promise<boolean> => {
  return new Promise((resolve) => {
    const webP = new Image()
    webP.onload = webP.onerror = () => {
      resolve(webP.height === 2)
    }
    webP.src =
      ''
  })
}

/**
 * 将File转换为Blob
 * @param file 文件对象
 * @returns Promise<Blob>
 */
export const fileToBlob = async (file: File): Promise<Blob> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()

    reader.onload = () => {
      const arrayBuffer = reader.result as ArrayBuffer
      const blob = new Blob([arrayBuffer], { type: file.type })
      resolve(blob)
    }

    reader.onerror = () => {
      reject(new Error('文件读取失败'))
    }

    reader.readAsArrayBuffer(file)
  })
}
